package com.web.controoller;

import com.web.pojo.domain.UserInfo;
import com.web.pojo.dto.UpdatePasswordDTO;
import com.web.pojo.vo.CommonResult;
import com.web.pojo.vo.Menu;
import com.web.service.LoginServer;
import com.web.utils.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: wws
 * describe:
 */
@CrossOrigin
@RestController
public class LoginController {

    @Autowired
    LoginServer loginServer;

    @PostMapping("/getMenu")
    @ApiOperation("查看用户菜单")
    public CommonResult getMenu() {
        Integer userId = SecurityUtils.getUserId();
        List<Menu> list = loginServer.getMenu(userId);
        return CommonResult.select(list);
    }

    @PostMapping("/getUserInfo")
    @ApiOperation("查看用户信息")
    public CommonResult getUserInfo() {
        Integer userId = SecurityUtils.getUserId();
        UserInfo userInfo = loginServer.getUserInfo(userId);
        return CommonResult.select(userInfo);
    }

    @PostMapping("/updatePersonalInfo")
    @ApiOperation("修改个人信息")
    public CommonResult updatePersonalInfo(@RequestBody UserInfo userInfo) {
        Integer userId = SecurityUtils.getUserId();
        userInfo.setUserId(userId);

        return CommonResult.update(loginServer.updatePersonalInfo(userInfo));
    }

    @PostMapping("/updatePersonalPassword")
    @ApiOperation("修改个人信息")
    public CommonResult updatePersonalPassword(@RequestBody UpdatePasswordDTO updatePassword) {
        Integer userId = SecurityUtils.getUserId();
        UserInfo userInfo = loginServer.checkPassword(userId);
        if (!SecurityUtils.checkPassword(updatePassword.getOldPassword(), userInfo.getPassword())) {
            return CommonResult.error("旧密码错误");
        }

        if (!updatePassword.getNewPassword().equals(updatePassword.getCheckPassword())) {
            return CommonResult.error("两次密码输入不同");
        }

        String newPassword = SecurityUtils.encryptPassword(updatePassword.getNewPassword());
        return CommonResult.update(loginServer.updatePassWord(userId, newPassword));
    }
}
